package com.famnote.randomchat;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;



import org.jivesoftware.smack.XMPPConnection;

/*
import ncsu.course.android.broadcastchat4.BroadcastChatService;
import ncsu.course.android.broadcastchat4.CreateRoomActivity;
import ncsu.course.android.broadcastchat4.FindRoomActivity;
import ncsu.course.android.broadcastchat4.R;
import ncsu.course.android.broadcastchat4.UserNameActivity;
import ncsu.course.android.broadcastchat4.BroadcastChat.ChatMessageBuilder;
import ncsu.course.android.broadcastchat4.BroadcastChat.ChatMessageChecker;
*/




import com.famnote.randomchat.util.SystemUiHider;
import com.svenkapudija.imagechooser.AlertDialogImageChooser;
import com.svenkapudija.imagechooser.ImageChooser;
import com.svenkapudija.imagechooser.ImageChooserListener;
import com.svenkapudija.imagechooser.StorageOption;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.MessageQueue;
import android.renderscript.Element;
import android.telephony.TelephonyManager;
//import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;


import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.provider.PrivacyProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.GroupChatInvitation;
import org.jivesoftware.smackx.PrivateDataManager;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferNegotiator;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;

import org.jivesoftware.smackx.muc.DefaultParticipantStatusListener;
import org.jivesoftware.smackx.muc.HostedRoom;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.ParticipantStatusListener;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.jivesoftware.smackx.packet.ChatStateExtension;
import org.jivesoftware.smackx.packet.LastActivity;
import org.jivesoftware.smackx.packet.OfflineMessageInfo;
import org.jivesoftware.smackx.packet.OfflineMessageRequest;
import org.jivesoftware.smackx.packet.SharedGroupsInfo;
import org.jivesoftware.smackx.provider.AdHocCommandDataProvider;
import org.jivesoftware.smackx.provider.DataFormProvider;
import org.jivesoftware.smackx.provider.DelayInformationProvider;
//import org.jivesoftware.smackx.provider.BytestreamsProvider;
import org.jivesoftware.smackx.provider.DiscoverInfoProvider;
import org.jivesoftware.smackx.provider.DiscoverItemsProvider;
import org.jivesoftware.smackx.provider.MUCAdminProvider;
import org.jivesoftware.smackx.provider.MUCOwnerProvider;
import org.jivesoftware.smackx.provider.MUCUserProvider;
import org.jivesoftware.smackx.provider.MessageEventProvider;
import org.jivesoftware.smackx.provider.MultipleAddressesProvider;
import org.jivesoftware.smackx.provider.RosterExchangeProvider;
import org.jivesoftware.smackx.provider.VCardProvider;
import org.jivesoftware.smackx.provider.XHTMLExtensionProvider;
//import org.jivesoftware.smackx.provider.IBBProviders;
import org.jivesoftware.smackx.provider.StreamInitiationProvider;
import org.jivesoftware.smackx.search.UserSearch;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

///import com.famnote.street.R;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import android.os.AsyncTask;

import android.provider.MediaStore;
import android.provider.Settings.Secure;

import android.media.ExifInterface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class GroupChat extends Activity {
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;

	
	private static final int LOAD_IMAGE_GALLERY = 0;
	
	
	// Debugging
    private static final String TAG = "GroupChat";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_READ 	= 1;
    public static final int MESSAGE_WRITE 	= 2;
    public static final int MESSAGE_TOAST 	= 3;
    
    public static final String ROOM_LIST 			= "room_list";
    private static final long FIND_ROOM_TIME_OUT 	= 2000;
    private ArrayList<String> existingRoomList 		= null;
    private static final int RANDOM_WAIT_WIN 		= 500;
    
    // Key names received from the BroadcastChatService Handler
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int INTENT_GET_USERNAME 	= 1;
    private static final int INTENT_CREATE_ROOM 	= 2;
    private static final int INTENT_FIND_ROOM		= 3;

	private VideoView mVideoView;
	private WebView mWebView;
    
    //private ArrayList<String> messages = new ArrayList<String>();
    private ArrayList<OneComment> messages = new ArrayList<OneComment>();
    
    private Handler mHandler = new Handler();
    
    private DiscussArrayAdapter mAdapter;
    
    
	// Layout Views
    //private TextView 	mTitle;
    private ListView 	mConversationView;
    private EditText 	mOutEditText;
    private Button 		mSendButton;

    // Array adapter for the conversation thread
    //private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Member object for the chat services
    //////private BroadcastChatService mChatService = null;
    
    
    // message format
    private static final String CMD 	= "cmd=";
    private static final String ROOM 	= "room=";
    private static final String BODY 	= "body=";
    private static final String CMD_FIND_ROOM 		= "1";
    private static final String CMD_ROOM_NAME_ACK 	= "2";
    private static final String CMD_MESSAGE 		= "3";
    private static final String DELIMITER			= "||";

	private static final int CHOOSER_IMAGE_REQUEST_CODE = 0;
        
    //user and room name
    //private String mUserName;
    //private String mRoomName = "room1";
    
    
    
    private SettingsDialog mDialog;
    private XMPPConnection connection;
    
    private String mPartner;
    
    
    private String mUserid;
    
    private MultiUserChat mMuc;
    
    private String mRoomid;
    private String mNickname;
    private String mRoomTitle;
    private String mRoomSubtitle;
    private String mRoomImageUrl;
    
    ProgressDialog progDailog;
    private ProgressDialog dialog;
    
    private Dialog mDashDialog;

    private ImageChooser imageChooser;
    
    private Activity activity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_group_chat2);

		//final View controlsView = findViewById(R.id.fullscreen_content_controls);
		//final View contentView = findViewById(R.id.fullscreen_content);
		//final View contentView = findViewById(R.id.list_messages);
		/////mList = (ListView)findViewById(R.id.listMessages);
        ////Log.i("RandomChat", "mList = " + mList);
        /////setListAdapter();
		
		activity = this;
		
		Bundle b = getIntent().getExtras();
		mRoomid = b.getString("roomid");
		mNickname = b.getString("nickname");
		
		
		mRoomTitle = b.getString("title");
		mRoomSubtitle = b.getString("subtitle");
		mRoomImageUrl = b.getString("bgurl");
		
		setTitle(mRoomTitle);
		
		
		mDashDialog = new Dialog(this);
		
		/*
		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.
		//mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
		mSystemUiHider = SystemUiHider.getInstance(this, mList, HIDER_FLAGS);
		mSystemUiHider.setup();
		mSystemUiHider
				.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
					// Cached values.
					int mControlsHeight;
					int mShortAnimTime;

					@Override
					@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
					public void onVisibilityChange(boolean visible) {
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
							// If the ViewPropertyAnimator API is available
							// (Honeycomb MR2 and later), use it to animate the
							// in-layout UI controls at the bottom of the
							// screen.
							if (mControlsHeight == 0) {
								mControlsHeight = controlsView.getHeight();
							}
							if (mShortAnimTime == 0) {
								mShortAnimTime = getResources().getInteger(
										android.R.integer.config_shortAnimTime);
							}
							controlsView
									.animate()
									.translationY(visible ? 0 : mControlsHeight)
									.setDuration(mShortAnimTime);
						} else {
							// If the ViewPropertyAnimator APIs aren't
							// available, simply show or hide the in-layout UI
							// controls.
							controlsView.setVisibility(visible ? View.VISIBLE
									: View.GONE);
						}

						if (visible && AUTO_HIDE) {
							// Schedule a hide().
							delayedHide(AUTO_HIDE_DELAY_MILLIS);
						}
					}
				});

		*/
		/*
		// Set up the user interaction to manually show or hide the system UI.
		contentView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (TOGGLE_ON_CLICK) {
					mSystemUiHider.toggle();
				} else {
					mSystemUiHider.show();
				}
			}
		});
		*/

		// Upon interacting with UI controls, delay any scheduled hide()
		// operations to prevent the jarring behavior of controls going away
		// while interacting with the UI.
		//findViewById(R.id.dummy_button).setOnTouchListener(
			//	mDelayHideTouchListener);
		
		
	
		/*
		messages.add("Performing com.famnote.randomchat.Chat activity launch");
    	// Add the incoming message to the list view
    	mHandler.post(new Runnable() {
    		public void run() {
    			setListAdapter();
    		}
    	});
    	*/
		
		
		/*
		mUserName = getResources().getString(R.string.you);
		*/
		/*
		// Dialog for getting the xmpp settings
        mDialog = new SettingsDialog(this);
        
        mHandler.post(new Runnable() {
            public void run() {
                mDialog.show();
            }
        });
        */
		
		
		/*
        // Dialog for getting the xmpp settings
        mDialog = new SettingsDialog(this);

        
        // Set a listener to show the settings dialog
        Button setup = (Button) this.findViewById(R.id.button_new);
        setup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                mHandler.post(new Runnable() {
                    public void run() {
                        mDialog.show();
                    }
                });
            }
        });
        //setup.setVisibility(View.GONE);
		*/
		
		
		//ModalDialog dlg = new ModalDialog();
        //dlg.showAlertDialog(this, "hollo");
        
        //mHandler.post(new Runnable() {
          //  public void run() {
            //    mDialog.show();
            //}
        //});
		
		/*
		BitmapDrawable drawable = (BitmapDrawable)getResources().getDrawable(R.drawable.home_bg);
		
		//Bitmap bm = drawable.getBitmap();

		//l.setBackgroundDrawable(drawable);
		
		//getWindow().setBackgroundDrawableResource(R.drawable.background_image);
		getWindow().setBackgroundDrawable(drawable);
		*/
		
		//imageLoader.DisplayImage(profile.get(MainActivity.KEY_THUMB_URL), thumb_image);

		//String image_url = "http://api.androidhive.info/images/sample.jpg";
		 
        // ImageLoader class instance
        ImageLoader imgLoader = new ImageLoader(getApplicationContext());
 
        // whenever you want to load an image from url
        // call DisplayImage function
        // url - image url to load
        // loader - loader image, will be displayed before getting image
        // image - ImageView
        
        //ImageView bgImageView = (ImageView)findViewById(R.id.imageView1);
        //imgLoader.DisplayImage(mRoomImageUrl, bgImageView);
		
        


        mVideoView = (VideoView)findViewById(R.id.videoView);
        mWebView = (WebView) findViewById(R.id.webview);
        
        
        //videoView.setVideoURI(Uri.parse("rtsp://tv.hindiworldtv.com:1935/live/getpnj"));
        
        //String path="http://www.ted.com/talks/download/video/8584/talk/761";
        //String path1="http://commonsware.com/misc/test2.3gp";

        //String path1 = "rtsp://media2.lsops.net:554/live/cnn_en_high.sdp";
        
        
        Uri uri = Uri.parse(mRoomImageUrl);
        
        String scheme = uri.getScheme();
        
        if (scheme.equals("rtsp")) {
    
        	mWebView.setVisibility(View.INVISIBLE);
        	mVideoView.setVisibility(View.VISIBLE);
        	
        	//mVideoView.setMediaController(new MediaController(this));
        	mVideoView.setVideoURI(uri);
        	mVideoView.requestFocus();
        	mVideoView.start();
       
        	String msg = getResources().getString(R.string.please_wait);
        	progDailog = ProgressDialog.show(this, "", msg, true);

        	mVideoView.setOnPreparedListener(new OnPreparedListener() {

        		public void onPrepared(MediaPlayer mp) {
        			// TODO Auto-generated method stub
        			progDailog.dismiss();
        		}
        	});
        } else if (scheme.equals("http")) {
        	
        	mVideoView.setVisibility(View.INVISIBLE);
        	mWebView.setVisibility(View.VISIBLE);
        	
            mWebView.getSettings().setJavaScriptEnabled(true); 
            //mWebView.loadUrl("http://push.appaas.com/directory/www");
            mWebView.loadUrl(mRoomImageUrl);
        }
        
        
        
        //mVideoView.setVideoURI(uri);
        //mVideoView.start();
        
        
        //YourAsyncTask yourAsyncTask = new YourAsyncTask();

        // Starting the download process
        //yourAsyncTask.execute();
        
		
		setupChat();
	}
	

	private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
		String videoUrl;
		
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(activity, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=1FJHYqE0RDg";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
/*
            videoView.setVideoURI(Uri.parse("rtsp://v4.cache1.c.youtube.com/CiILENy73wIaGQk4RDShYkdS1BMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"));
            videoView.setMediaController(new MediaController(AlertDetail.this));
            videoView.requestFocus();
            videoView.start();*/            
            mVideoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(activity);
            mVideoView.setMediaController(mc);
            mVideoView.requestFocus();
            mVideoView.start();          
            mc.show();
        }

    }

	public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            
            org.w3c.dom.Element el = doc.getDocumentElement();
            
            NodeList list = el.getElementsByTagName("media:content"); ///media:content
           
            
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

	protected static String extractYoutubeId(String url) throws MalformedURLException
    {
        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }	
	
	
	
	
	
	public class ModalDialog {

		private boolean mChoice = false;        
		private boolean mQuitModal = false;     

		private Method mMsgQueueNextMethod = null;
		private Field mMsgTargetFiled = null;

		public ModalDialog() {
		}

		public void showAlertDialog(Context context, String info) {
		    if (!prepareModal()) {
		        return;
		    }

		    // build alert dialog
		    AlertDialog.Builder builder = new AlertDialog.Builder(context);
		    builder.setMessage(info);
		    builder.setCancelable(false);
		    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		            ModalDialog.this.mQuitModal = true;
		            dialog.dismiss();
		        }
		    });

		    AlertDialog alert = builder.create();
		    alert.show();

		    // run in modal mode
		    doModal();
		}

		public boolean showConfirmDialog(Context context, String info) {
		    if (!prepareModal()) {
		        return false;
		    }

		    // reset choice
		    mChoice = false;

		    AlertDialog.Builder builder = new AlertDialog.Builder(context);
		    builder.setMessage(info);
		    builder.setCancelable(false);
		    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		            ModalDialog.this.mQuitModal = true;
		            ModalDialog.this.mChoice = true;
		            dialog.dismiss();
		        }
		    });

		    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		            ModalDialog.this.mQuitModal = true;
		            ModalDialog.this.mChoice = false;
		            dialog.cancel();
		        }
		    });

		    AlertDialog alert = builder.create();
		    alert.show();

		    doModal();
		    return mChoice;
		}

		private boolean prepareModal() {
		    Class<?> clsMsgQueue = null;
		    Class<?> clsMessage = null;

		    try {
		        clsMsgQueue = Class.forName("android.os.MessageQueue");
		    } catch (ClassNotFoundException e) {
		        e.printStackTrace();
		        return false;
		    }

		    try {
		        clsMessage = Class.forName("android.os.Message");
		    } catch (ClassNotFoundException e) {
		        e.printStackTrace();
		        return false;
		    }

		    try {
		        mMsgQueueNextMethod = clsMsgQueue.getDeclaredMethod("next", new Class[]{});
		    } catch (SecurityException e) {
		        e.printStackTrace();
		        return false;
		    } catch (NoSuchMethodException e) {
		        e.printStackTrace();
		        return false;
		    }

		    mMsgQueueNextMethod.setAccessible(true);

		    try {
		        mMsgTargetFiled = clsMessage.getDeclaredField("target");
		    } catch (SecurityException e) {
		        e.printStackTrace();
		        return false;
		    } catch (NoSuchFieldException e) {
		        e.printStackTrace();
		        return false;
		    }

		    mMsgTargetFiled.setAccessible(true);
		    return true;
		}

		private void doModal() {
		    mQuitModal = false;

		    // get message queue associated with main UI thread
		    MessageQueue queue = Looper.myQueue();
		    while (!mQuitModal) {
		        // call queue.next(), might block
		        android.os.Message msg = null;
		        try {
		            msg = (android.os.Message)mMsgQueueNextMethod.invoke(queue, new Object[]{});
		        } catch (IllegalArgumentException e) {
		            e.printStackTrace();
		        } catch (IllegalAccessException e) {
		            e.printStackTrace();
		        } catch (InvocationTargetException e) {
		            e.printStackTrace();
		        }

		        if (null != msg) {
		            Handler target = null;
		            try {
		                target = (Handler)mMsgTargetFiled.get(msg);
		            } catch (IllegalArgumentException e) {
		                e.printStackTrace();
		            } catch (IllegalAccessException e) {
		                e.printStackTrace();
		            }

		            if (target == null) {
		                // No target is a magic identifier for the quit message.
		                mQuitModal = true;
		            }

		            target.dispatchMessage(msg);
		            msg.recycle();
		        }
		    }
		}
		}
	
	
	
	

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		
		//////////delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	/*
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				d
				elayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};
	*/

	/*
	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};
	*/

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	/*
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}
	
	*/
	
	
	
	
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");


    }
	
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
        /////////if (mChatService != null) mChatService.stop();
        
    }

    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "- ON RESUME -");
        
        //if (connection == null) {
        	//setupChat();
        //}
    }

    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
        //////////if (mChatService != null) mChatService.stop();
 
    }


    public void onDestroy() {
        super.onDestroy();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
        // Stop the Broadcast chat services
        //////////if (mChatService != null) mChatService.stop();
        
        
        if (mMuc != null) {
        	mMuc.leave();
        	mMuc = null;
        }
        
        
        if (connection != null) {
        	connection.disconnect();
        	connection = null;
        }
        
    }
    
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_BACK) { 

        	//String msg = getResources().getString(R.string.room_leaving);
        	//dialog = ProgressDialog.show(this, "", msg, true);
        
        	LeaveRoomTask task = new LeaveRoomTask();
        	
        	task.execute("http://push.appaas.com/hulbox/of_leave_room.php?roomid=" + mRoomid
        			+ "&userid=" + mUserid);
        	
            return true; 
        } 
        return super.onKeyDown(keyCode, event);
    }
    
    
    
    
    /** AsyncTask */
    private class LeaveRoomTask extends AsyncTask<String, Integer, String>{
        String data = null;
    	
        @Override
        protected String doInBackground(String... url) {
                
        	try{
        		
        		
                if (mMuc != null) {
                
                	mMuc.removeMessageListener(packetListener);
                	mMuc.removeParticipantStatusListener(participantStatusListener);
                	
                   	mMuc.leave();
                   	
                	mMuc = null;
                	
                }
                
                
                if (connection != null) {
                	
                	connection.disconnect();
                	
                	connection = null;
                }
                
                
        		data = downloadUrl(url[0]);
                                
            }catch(Exception e){
            	Log.d("Background Task",e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
                	
        	//dialog.dismiss();

        	finish();
        	
        	
        }
    }
	
	
    private void setupChat() {
        //Log.d(TAG, "setupChat()");

        // Initialize the array adapter for the conversation thread
        //mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        //mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item);
        mConversationView = (ListView) findViewById(R.id.listView1);
        //mConversationView.setAdapter(mConversationArrayAdapter);

        messages.clear();
        
        /*
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        
        messages.add(new OneComment(true, "^^"));
		*/
        
        mAdapter = new DiscussArrayAdapter(this, R.layout.listitem_discuss, messages);
        mConversationView.setAdapter(mAdapter);
        
        /*
        mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        
        mOutEditText.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					mAdapter.add(new OneComment(false, mOutEditText.getText().toString()));
					////mConversationView.setSelection(mAdapter.getCount() -1);
					
					
					
					try {
		        		
			            if (mPartner != null) {
		            		Message msg = new Message(mPartner, Message.Type.chat);
		            		msg.setBody(mOutEditText.getText().toString());
		            		connection.sendPacket(msg);
		            	}
		        		
			            
			            
					} catch (Exception e) {
						e.printStackTrace();
					}
		        	
					
					mOutEditText.setText("");
					
					
					return true;
				}
				return false;
			}
		});
		*/
        
        
        
        // Initialize the compose field with a listener for the return key
        //mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        
        //mOutEditText.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	if(D) Log.e(TAG, "[sendButton clicked]");
            	
            	/*
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                sendMessage(message);        
                */
            	
            	mOutEditText = (EditText) findViewById(R.id.edit_text_out);
            	String message = mOutEditText.getText().toString();
            	
            
            	if (message.equals("")) return;
           	
            	
            	/*
            	messages.add(message);
            	// Add the incoming message to the list view
            	mHandler.post(new Runnable() {
            		public void run() {
            			//setListAdapter();
            			//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item, messages);
            	        //DiscussArrayAdapter<OneComment> adapter =
            	        	//	new DiscussArrayAdapter<OneComment>(getApplicationContext(), R.layout.listitem_discuss, comments);
            	        //adapter.add(new OneComment(false, message));
            	        
            	        mConversationView.setAdapter(adapter);
            	        
            	        mConversationView.setSelection(adapter.getCount() -1);
            		}
            	});
            	*/
            	
            	/*
            	if (mRoomid != null) {
            		//Chat chat = connection.getChatManager().createChat("room1@")
            		try {
            			String to = mRoomid + "";
	            		Message msg = new Message(to, Message.Type.chat);
	            		msg.setBody(message);
	            		connection.sendPacket(msg);
	            	} catch (Exception e) {
	            		e.printStackTrace();
	            	}
            	}
            	*/
            	

            	//String room = mRoomid + "@conference.push.appaas.com";
        		try {
        			/*
                	Message msg = new Message(room, Message.Type.groupchat);
            		msg.setBody(message);
            		connection.sendPacket(msg);
            		*/
        			
            		mMuc.sendMessage(message);
            		
            	} catch (Exception e) {
            		e.printStackTrace();
            	}
        		

        		////messages.add(new OneComment(false, mNickName, message));
        		////if (messages.size() > 100) { messages.remove(0); }
            	
        		/*
        		// Add the incoming message to the list view
            	mHandler.post(new Runnable() {
            		public void run() {
            			setListAdapter();
            		}
            	});
            	*/
        		
        		mAdapter.notifyDataSetChanged();
        		mConversationView.setSelection(messages.size()-1);
            	
        		
        		mOutEditText.setText("");
        		/*
        		messages.add(new OneComment(false, message));
        		if (messages.size() > 100) { messages.remove(0); }
            	// Add the incoming message to the list view
            	mHandler.post(new Runnable() {
            		public void run() {
            			setListAdapter();
            			mOutEditText.setText("");
            		}
            	});
            	*/
            	
            	/*
            	if (mPartner == null) {
            		String notice = getResources().getString(R.string.no_partner);
            		
            		//mAdapter.add(new OneComment(true, notice));
            		//mConversationView.setSelection(mAdapter.getCount() -1);
            		
            		messages.add(new OneComment(true, notice));
            		if (messages.size() > 100) { messages.remove(0); }
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                			mOutEditText.setText("");
                		}
                	});
            		
            	} else {
            		try {
	            		Message msg = new Message(mPartner, Message.Type.chat);
	            		msg.setBody(message);
	            		connection.sendPacket(msg);
	            	} catch (Exception e) {
	            		e.printStackTrace();
	            	}
	        	
            		//mAdapter.add(new OneComment(false, message));
            		//mConversationView.setSelection(mAdapter.getCount() -1);
            		
            		messages.add(new OneComment(false, message));
            		if (messages.size() > 100) { messages.remove(0); }
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                			mOutEditText.setText("");
                		}
                	});
                	
                	
            	}
            	*/
            	
				
				
            	
            }
        });
        
        
        

        
        
        

        /*********************
        // Initialize the BluetoothChatService to perform bluetooth connections
        if(mChatService == null)
        	mChatService = new BroadcastChatService(this, mHandler);
        	*********************/

        // Initialize the buffer for outgoing messages
        if(mOutStringBuffer == null)
        	mOutStringBuffer = new StringBuffer("");
        
        
        
        
        /*
        Thread t = new Thread(new Runnable(){
        	@Override
        	public void run() {
        		
        		// no UI
        		mHandler.post(new Runnable(){
        			@Override
        			public void run() {
        				// UI OK
        				
        				if(D) Log.e(TAG, "++ XMPP connect ++");
        		        
        				ConnectionConfiguration connConfig =
        		        		new ConnectionConfiguration("push.appaas.com", 5222, "push.appaas.com");
        		        connConfig.setSASLAuthenticationEnabled(true);
        		        connConfig.setDebuggerEnabled(true);
        		        
        		        
        		        XMPPConnection connection = new XMPPConnection(connConfig);
        		        

        		        if(D) Log.e(TAG, "++ connection.connect() ++");
        		        
        		        try {
        		            connection.connect();
        		            
        		            if(D) Log.e(TAG, "++ after connection.connect() ++");
        		            
        		            
        		            
        		            connection.loginAnonymously();
        		            //Log.i("XMPPClient", "Logged in as " + connection.getUser());
        		            if(D) Log.e(TAG, "++ connection.loginAnonymously() ++");
        		            
        		            setConnection(connection);
        		            
        		        } catch (XMPPException ex) {
        		            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
        		            Log.e("XMPPClient", ex.toString());
        		            
        		            setConnection(null);
        		        }
        				

        			}
        		});
        	}
        	
        });
        
        t.start();
        */
        
        String msg = getResources().getString(R.string.connecting_to_server);
        dialog = ProgressDialog.show(this, "", msg, true);
        
        new processXmppTask().execute("a", "b", "c");
        
        //setConnection(connection);
                
    }
	
    /*
    private class processXmppTask extends AsyncTask<void, void, void> {
    	
    	@Override
    	protected void doInBackground(void... parmams) {
    		
    	}
    }
    */
    
    private class processXmppTask extends AsyncTask<String, Integer, Long> {
    	
    	@Override
    	protected Long doInBackground(String... urls) {

    		
    		
    		long totalSize = 0;
            
            
    		if(D) Log.e(TAG, "++ XMPP connect ++");
	        
			ConnectionConfiguration connConfig =
	        		new ConnectionConfiguration("push.appaas.com", 5222, "push.appaas.com");
	        //connConfig.setSASLAuthenticationEnabled(true);
	        //connConfig.setDebuggerEnabled(true);
	        
	        
			XMPPConnection connection = new XMPPConnection(connConfig);
	        

	        if(D) Log.e(TAG, "++ connection.connect() ++");
	        
	        try {
	            connection.connect();
	            
	            if(D) Log.e(TAG, "++ after connection.connect() ++");

	            connection.loginAnonymously();
	            
	            //connection.login("creath", "1234");
	            
	            //Log.i("XMPPClient", "Logged in as " + connection.getUser());
	            if(D) Log.e(TAG, "++ connection.loginAnonymously() ++");
	          
	            //mUserName = StringUtils.parseBareAddress(connection.getUser());
	            //if(D) Log.e(TAG, mUserName);
	            
	            mUserid = StringUtils.parseName(connection.getUser());
	            
	            
	            ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
	            if (sdm == null) sdm = new ServiceDiscoveryManager(connection);    
	            sdm.addFeature("http://jabber.org/protocol/disco#info");
	            sdm.addFeature("jabber:iq:privacy");
	            
	            
	            configure();
	            
	            
	            
	            //if(D) Log.e(TAG, mRoom);
	            
	            
	            //String nickName = StringUtils.parseName(connection.getUser());
	        	
	            // Discover information about the room roomName@conference.myserver
	            //RoomInfo roomInfo = MultiUserChat.getRoomInfo(connection, mRoom);
	            
	            //int oCount = roomInfo.getOccupantsCount();
	            
	            //mNickName = getResources().getString(R.string.anonymous) + String.valueOf(oCount+1);

	            ///////mNickName = StringUtils.parseName(connection.getUser());

	            

	            /*
		        try {
		        	//TelephonyManager tel_manager = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
		            //String deviceid = tel_manager.getDeviceId();
		        	String androidid = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		        	
		        	String url = "http://push.appaas.com/hulbox/of_nickname.php?deviceid=" + androidid + "&roomid=" + mRoomid;
			        mNickName = downloadUrl(url);

	            }catch(Exception e){
	            	Log.d("downloadUrl",e.toString());
	            	
	            	mNickName = getResources().getString(R.string.anonymous);
	            }  
				*/
	            
		        
		        if (mRoomid == null) {
		        	
		            mRoomid = mUserid;
		            	
		            String room = mRoomid + "@conference.push.appaas.com";
		            mMuc = new MultiUserChat(connection, room);
		            mMuc.join(mNickname);
		            	
		   	        // Send an empty room configuration form which indicates that we want an instant room
		            mMuc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
			        
			        /*
			        Form submitForm = mMuc.getConfigurationForm().createAnswerForm();
			        //submitForm.setAnswer("muc#roomconfig_publicroom", false);
			        submitForm.setAnswer("muc#roomconfig_roomdesc", mRoomTitle);
			        mMuc.sendConfigurationForm(submitForm);
			        */
			        
			        /*
			        Form form = mMuc.getConfigurationForm();
			        Form submitForm = form.createAnswerForm();
		            // Add default answers to the form to submit
		            for (Iterator fields = form.getFields(); fields.hasNext();) {
		                FormField field = (FormField) fields.next();
		                if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
		                    // Sets the default value as the answer
		                    submitForm.setDefaultAnswer(field.getVariable());
		                }
		            }
		            submitForm.setAnswer("muc#roomconfig_roomdesc", mRoomTitle);
		            mMuc.sendConfigurationForm(form);
			        */
			        
			        //Form form = mMuc.getConfigurationForm();
			        //form.setAnswer("muc#roomconfig_roomdesc", mRoomTitle);
			        //mMuc.sendConfigurationForm(form);
			        
			      //submitForm.setAnswer("muc#roomconfig_roomowners", owners);
		            //submitForm.setAnswer("muc#roomconfig_maxusers", 2);
		            // Send the completed form (with default values) to the server to configure the room
		            //muc.sendConfigurationForm(submitForm);
		            
		            
			        
			        //mMuc.addParticipantListener(packetListener);
			        mMuc.addMessageListener(packetListener);
			        
			        mMuc.addParticipantStatusListener(participantStatusListener);
			        
			        setConnection(connection);
			           
			          
			        
		        } else {
		            	
		        	String room = mRoomid + "@conference.push.appaas.com";
		        	mMuc = new MultiUserChat(connection, room);
		        	mMuc.join(mNickname);
		            
		            
		            
		            //mMuc.addParticipantListener(packetListener);
		            mMuc.addMessageListener(packetListener);
		            mMuc.addParticipantStatusListener(participantStatusListener);
		            
		            /*
		            mMuc.addParticipantStatusListener(new ParticipantStatusListener() {
		                public void joined(String participant) {
		                    super.joined(participant);
		                    
		                    
		                    if ((room + "/testbot2").equals(participant)) {
		                        answer[0] = participant;
		                    }
		                    else {
		                        answer[1] = participant;
		                    }
		                    
		                }
		                public void left(String participant) {
		                    super.left(participant);
		                    
		                    
		                    if ((room + "/testbot2").equals(participant)) {
		                        answer[2] = participant;
		                    }
		                    // Skip unavailable presences of the same user
		                    else if (!(room + "/testbot").equals(participant)) {
		                        answer[3] = participant;
		                    }
		                    
		                }
		            });
		            */

		            
		            setConnection(connection);

		        }
		        


		        try {
		        	String url = "http://push.appaas.com/hulbox/of_join_room.php?roomid=" + mRoomid
		        			+ "&userid=" + mUserid
		        			+ "&nickname=" + URLEncoder.encode(mNickname, "utf-8")
		        			+ "&title=" + URLEncoder.encode(mRoomTitle, "utf-8")
		        			+ "&subtitle=" + URLEncoder.encode(mRoomSubtitle, "utf-8");
			        downloadUrl(url);

	            }catch(Exception e){
	            	Log.d("downloadUrl",e.toString());
	            }    
	            


	            
	            /*
	         // Get the the room's configuration form
	            Form form = muc.getConfigurationForm();
	            // Create a new form to submit based on the original form
	            Form submitForm = form.createAnswerForm();
	            // Add default answers to the form to submit
	            for (Iterator fields = form.getFields(); fields.hasNext();) {
	                FormField field = (FormField) fields.next();
	                if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
	                    // Sets the default value as the answer
	                    submitForm.setDefaultAnswer(field.getVariable());
	                }
	            }
	            // Sets the new owner of the room
	            //List owners = new ArrayList();
	            //owners.add("johndoe@jabber.org");
	            //submitForm.setAnswer("muc#roomconfig_roomowners", owners);
	            submitForm.setAnswer("muc#roomconfig_maxusers", 2);
	            // Send the completed form (with default values) to the server to configure the room
	            muc.sendConfigurationForm(submitForm);
	            */
	            
	            
	            
	            
	            /*
	            Iterator<String> itr = muc.getOccupants();
	            
	            while(itr.hasNext()) {
	            	String occupant = itr.next();
	            	messages.add(new OneComment(true, StringUtils.parseResource(occupant)));
	            	if (messages.size() > 100) { messages.remove(0); }
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                		}
                	});
	            }
	            */
	            
	            
	            
	         // Discover information about the room roomName@conference.myserver
	            //RoomInfo roomInfo = MultiUserChat.getRoomInfo(connection, mRoom);
	            
	            //int oCount = roomInfo.getOccupantsCount();
	            
	            
	            
	        	
	            
	            
	            
	            /*
	         // Create a MultiUserChat using a Connection for a room
	            MultiUserChat muc = new MultiUserChat(connection, "@conference.push.appaas.com");

	            // Create the room
	            //muc.create("testbot");
	            muc.join("testbot");

	            // Send an empty room configuration form which indicates that we want
	            // an instant room
	            muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
	            */
	            
	            
	        } catch (XMPPException ex) {
	            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
	            Log.e("XMPPClient", ex.toString());
	            
	            setConnection(null);

	        }
	        
    		dialog.dismiss();
	        
    		dialog = null;
    		
    		
    		// Add the incoming message to the list view
			mHandler.post(new Runnable() {
				public void run() {
					//setListAdapter();
					mAdapter.notifyDataSetChanged();
					mConversationView.setSelection(messages.size()-1);
				}
			});
    		
    		
    		
    		return totalSize;
    	}
    	
    	/*
    	@Override
        protected void onPostExecute(String result) {
    		
    		dialog.dismiss();
    	}
    	*/
    	
    }
    
    
    

    
    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                /////////sendMessage(message);
                
            	mAdapter.add(new OneComment(false, "", message));
            	
            	
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };
    
    
    private void HttpFileUpload(String urlString, String params, String fileName) {
    	
    	String lineEnd = "\r\n";
    	String twoHyphens = "--";
    	String boundary = "*****";
    	
    	
		try {
			
			FileInputStream mFileInputStream = new FileInputStream(fileName);			
			URL connectUrl = new URL(urlString);
			Log.d("Test", "mFileInputStream  is " + mFileInputStream);
			
			// open connection 
			HttpURLConnection conn = (HttpURLConnection)connectUrl.openConnection();			
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			
			String uid = "1091";
			
			// write data
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			
			/*
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"uid\"" + lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(uid);
			*/
			
			
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"uploadedImage\";filename=\"" + fileName+"\"" + lineEnd);
			dos.writeBytes(lineEnd);
			

			
			int bytesAvailable = mFileInputStream.available();
			int maxBufferSize = 1024;
			int bufferSize = Math.min(bytesAvailable, maxBufferSize);
			
			byte[] buffer = new byte[bufferSize];
			int bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
			
			Log.d("Test", "image byte is " + bytesRead);
			
			// read image
			while (bytesRead > 0) {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = mFileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
			}	
			
			dos.writeBytes(lineEnd);
			
			
			dos.writeBytes(twoHyphens + boundary + lineEnd);
		    dos.writeBytes("Content-Disposition: form-data; name=\"uid\"" + lineEnd);
		    dos.writeBytes(lineEnd);
		    dos.writeBytes(uid);
		    dos.writeBytes(lineEnd);
			
		    dos.writeBytes(twoHyphens + boundary + lineEnd);
		    dos.writeBytes("Content-Disposition: form-data; name=\"width\"" + lineEnd);
		    dos.writeBytes(lineEnd);
		    dos.writeBytes("0");
		    dos.writeBytes(lineEnd);
		    
		    dos.writeBytes(twoHyphens + boundary + lineEnd);
		    dos.writeBytes("Content-Disposition: form-data; name=\"height\"" + lineEnd);
		    dos.writeBytes(lineEnd);
		    dos.writeBytes("0");
		    dos.writeBytes(lineEnd);
		    
		    
		    
		    
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
			
			
			/*
			dos.writeBytes(twoHyphens + boundary + lineEnd);
		    dos.writeBytes("Content-Disposition: form-data; name=\"uid\"" + lineEnd);
		    dos.writeBytes(lineEnd);
		    dos.writeBytes(uid);
		    //dos.writeBytes(lineEnd);
			*/
			
			
			
			// close streams
			Log.e("Test" , "File is written");
			mFileInputStream.close();
			dos.flush(); // finish upload...			
			
			// get response
			int ch;
			InputStream is = conn.getInputStream();
			StringBuffer b =new StringBuffer();
			while( ( ch = is.read() ) != -1 ){
				b.append( (char)ch );
			}
			String s=b.toString(); 
			Log.e("Test", "result = " + s);
			
			//mEdityEntry.setText(s);
			dos.close();			
			
		} catch (Exception e) {
			Log.d("Test", "exception " + e.getMessage());
			// TODO: handle exception
		}		
	}
    
    
    /** AsyncTask to download xml data */
    private class HttpFileUploadTask extends AsyncTask<String, Integer, String>{
        String data = null;
                
        @Override
        protected String doInBackground(String... params) {
        	
        	String fileName = params[0];
        	
        	
        	/*
                        try{
                            data = downloadUrl(url[0]);
                                
                        }catch(Exception e){
                        	Log.d("Background Task",e.toString());
                        }
                        if(D) Log.e(TAG, "popup_url: " + data);
                        
                        return data;
                   */
        	
        	//HttpFileUpload("http://push.appaas.com/lemon/tencoon/upload.php", "", filePath);
        	
        	String filePath = getExternalFilesDir(null).getAbsolutePath() + "/myDirectory" + "/myFabulousImage.jpg";
        	
        	if(D) Log.e(TAG, "filePath: " + filePath);
        	
        	String urlString = "http://push.appaas.com/lemon/tencoon/upload.php";
        	
        	String lineEnd = "\r\n";
        	String twoHyphens = "--";
        	String boundary = "*****";
        	
        	
    		try {
    			
    			FileInputStream mFileInputStream = new FileInputStream(filePath);			
    			URL connectUrl = new URL(urlString);
    			Log.d("Test", "mFileInputStream  is " + mFileInputStream);
    			
    			// open connection 
    			HttpURLConnection conn = (HttpURLConnection)connectUrl.openConnection();			
    			conn.setDoInput(true);
    			conn.setDoOutput(true);
    			conn.setUseCaches(false);
    			conn.setRequestMethod("POST");
    			conn.setRequestProperty("Connection", "Keep-Alive");
    			conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    			
    			String uid = "1091";
    			///////String + "&nickname=" + URLEncoder.encode(mNickname, "utf-8")
    			
    			// write data
    			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
    			
    			/*
    			dos.writeBytes(twoHyphens + boundary + lineEnd);
    			dos.writeBytes("Content-Disposition: form-data; name=\"uid\"" + lineEnd);
    			dos.writeBytes(lineEnd);
    			dos.writeBytes(uid);
    			*/
    			
    			
    			dos.writeBytes(twoHyphens + boundary + lineEnd);
    			dos.writeBytes("Content-Disposition: form-data; name=\"uploadedImage\";filename=\"" + fileName+"\"" + lineEnd);
    			dos.writeBytes(lineEnd);
    			

    			
    			int bytesAvailable = mFileInputStream.available();
    			int maxBufferSize = 1024;
    			int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    			
    			byte[] buffer = new byte[bufferSize];
    			int bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
    			
    			Log.d("Test", "image byte is " + bytesRead);
    			
    			// read image
    			while (bytesRead > 0) {
    				dos.write(buffer, 0, bufferSize);
    				bytesAvailable = mFileInputStream.available();
    				bufferSize = Math.min(bytesAvailable, maxBufferSize);
    				bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
    			}	
    			
    			dos.writeBytes(lineEnd);
    			
    			
    			dos.writeBytes(twoHyphens + boundary + lineEnd);
    		    dos.writeBytes("Content-Disposition: form-data; name=\"uid\"" + lineEnd);
    		    dos.writeBytes(lineEnd);
    		    dos.writeBytes(uid);
    		    dos.writeBytes(lineEnd);
    			
    		    dos.writeBytes(twoHyphens + boundary + lineEnd);
    		    dos.writeBytes("Content-Disposition: form-data; name=\"width\"" + lineEnd);
    		    dos.writeBytes(lineEnd);
    		    dos.writeBytes("0");
    		    dos.writeBytes(lineEnd);
    		    
    		    dos.writeBytes(twoHyphens + boundary + lineEnd);
    		    dos.writeBytes("Content-Disposition: form-data; name=\"height\"" + lineEnd);
    		    dos.writeBytes(lineEnd);
    		    dos.writeBytes("0");
    		    dos.writeBytes(lineEnd);
    		    
    		    
    		    
    		    
    			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    			
    			
    			/*
    			dos.writeBytes(twoHyphens + boundary + lineEnd);
    		    dos.writeBytes("Content-Disposition: form-data; name=\"uid\"" + lineEnd);
    		    dos.writeBytes(lineEnd);
    		    dos.writeBytes(uid);
    		    //dos.writeBytes(lineEnd);
    			*/
    			
    			
    			
    			// close streams
    			Log.e("Test" , "File is written");
    			mFileInputStream.close();
    			dos.flush(); // finish upload...			
    			
    			// get response
    			int ch;
    			InputStream is = conn.getInputStream();
    			StringBuffer b =new StringBuffer();
    			while( ( ch = is.read() ) != -1 ){
    				b.append( (char)ch );
    			}
    			String s=b.toString(); 
    			Log.e("Test", "result = " + s);
    			
    			//mEdityEntry.setText(s);
    			dos.close();			
    			
    		} catch (Exception e) {
    			Log.d("Test", "exception " + e.getMessage());
    			// TODO: handle exception
    		}
    		
    		
    		return data;
        }

        @Override
        protected void onPostExecute(String result) {
                	
        	
        	
             dialog.dismiss();
            
             /*
             if ((data != null) && (data != "")) {
                	final Dialog popupDlg = new Dialog(activity);
            		popupDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
            		popupDlg.setContentView(R.layout.popup);
            		popupDlg.setCancelable(true);

                    WebView webView = (WebView) popupDlg.findViewById(R.id.webview);
                    webView.getSettings().setJavaScriptEnabled(true);
                    //webView.loadUrl("http://en.wikipedia.org/wiki/" + name.getText().toString());
                    //webView.loadUrl("http://en.wikipedia.org/wiki/" + "gold");
                    //webView.loadUrl("http://blog.naver.com/swingfish");
                    webView.loadUrl(data);
                    webView.setWebViewClient(new WebViewClientClass());
                    
                  
                    Button button = (Button) popupDlg.findViewById(R.id.close);
                    button.setOnClickListener(new OnClickListener() {
            		    public void onClick(View v) {
            		    	popupDlg.dismiss();
            		    }
            		});

                       
                    //dialog.show();
            		
                    
                    mHandler.post(new Runnable() {
                        public void run() {
                        	popupDlg.show();
                        }
                    });
            		
             }
             */
                	
        }
    }
    
    
    
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
       
        
        if (requestCode == CHOOSER_IMAGE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {

        	String msg = getResources().getString(R.string.uploading);
            dialog = ProgressDialog.show(activity, "", msg, true);
        	
            imageChooser.onActivityResult(this, data, new ImageChooserListener() {

                @Override
                public void onResult(Bitmap image, File savedImage) {
                    // Do something with original image...

                    // savedImage is null if you didn't invoke any
                    // saveImageTo method
                	
                	
                	///////imageChooser.saveImageTo(StorageOption.SD_CARD_APP_ROOT, "myDirectory", "myFabulousImage");
                	
                	
                	
                	
                	
                	//HttpFileUpload("http://push.appaas.com/lemon/tencoon/upload.php", "", filePath);
                	
                	
                	
                	
                	String fileName = savedImage.getName();
                	
                	HttpFileUploadTask task = new HttpFileUploadTask();
                    task.execute(fileName);
                	
                }

                @Override
                public void onError(String message) {
                    // Something bad happened :(
                	
                	dialog.dismiss();
                	
                }
            });
            
        }
        
        
        else if (requestCode == LOAD_IMAGE_GALLERY && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();


            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            if(D) Log.d(TAG, "picturePath " + picturePath);

            /*
            ExifInterface exifMedia;
			try {
                exifMedia = new ExifInterface(picturePath);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String exifOrint = exifMedia.getAttribute(ExifInterface.TAG_ORIENTATION);

            int exifOrientation = Integer.parseInt(exifOrint);

            System.out.println("Orientation Tag is:"+exifOrientation);

            System.out.println("Path Of the Image " + picturePath);

            BitmapFactory.Options mOptions=new BitmapFactory.Options();
            mOptions.inSampleSize=2;
            Bitmap imgBitmap = BitmapFactory.decodeFile(picturePath, mOptions);
            Runtime.getRuntime().gc();

            imgBitmap = MyProfileActivity.getResizedBitmapImage(imgBitmap, 60, 60, exifOrientation);
            MessageImageBitmap msgImgBitmap = new MessageImageBitmap();
            msgImgBitmap.setImgBitmap(imgBitmap);
            msgImgBitmap.setImgPath(picturePath);

            MessagePacket packetMsg = new MessagePacket();
            packetMsg.setMsgBitmap(msgImgBitmap);
            packetMsg.setIsSendPacket(true);
            packetMsg.setMessageType(MessagePacket.MESSAGE_TYPE_IMAGE);
            packetMsg.setIMAGE_PATH(picturePath);

            messageWithImage.add(packetMsg);

            customAdapter1.notifyDataSetChanged();
            mList.setSelection(mList.getCount());

            String to = frienduserID;
            dbhHelper.insertMessage(CCMStaticVariable.loginUserId
                    + "@ec202.classicinformatics.com", refineFromjId(to), "",
                    "true", picturePath, 1);

            sendFile(picturePath, frienduserID);
			*/
            
            
            picturePath = "/mnt/sdcard/DCIM/1km/2605567_111265912.jpg";

            
            FileTransferManager manager = new FileTransferManager(connection);
            OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(mPartner);
            File file = new File(picturePath);
            try {
               transfer.sendFile(file, "test_file");
            } catch (XMPPException e) {
               e.printStackTrace();
            }
            
           
            
            while(!transfer.isDone()) {
               if(transfer.getStatus().equals(FileTransfer.Status.error)) {
                  //System.out.println("ERROR!!! " + transfer.getError());
                  if(D) Log.d(TAG, "ERROR!!! " + transfer.getError());
               } else if (transfer.getStatus().equals(FileTransfer.Status.cancelled)
                                || transfer.getStatus().equals(FileTransfer.Status.refused)) {
                  //System.out.println("Cancelled!!! " + transfer.getError());
            	   if(D) Log.d(TAG, "Cancelled!!! " + transfer.getError()); 
               }
               try {
                  Thread.sleep(1000L);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }
            if(transfer.getStatus().equals(FileTransfer.Status.refused) || transfer.getStatus().equals(FileTransfer.Status.error)
             || transfer.getStatus().equals(FileTransfer.Status.cancelled)){
               //System.out.println("refused cancelled error " + transfer.getError());
            	if(D) Log.d(TAG, "refused cancelled error " + transfer.getError());
            } else {
               //System.out.println("Success");
               if(D) Log.d(TAG, "Success");
            }
            
            
            
            
            
            
            
            return;
        }
        
        
        
        
        switch (requestCode) {
       
        /*
        case INTENT_GET_USERNAME:            
            // When user name input dialog returns
            if (resultCode == Activity.RESULT_OK ) {
            	
            	mUserName = data.getExtras().getString(UserNameActivity.EXTRA_USER_NAME);
            	
            	Toast.makeText(this, "User name changed to "+mUserName, Toast.LENGTH_SHORT).show();
            	
            } else {
                
                Toast.makeText(this, R.string.username_error, Toast.LENGTH_SHORT).show();
            }
            break;
          */  
            
            
             // when create room dialog returns
        /****************    
        case INTENT_CREATE_ROOM:
        	if (resultCode == Activity.RESULT_OK ) {
            	
        		mRoomName = data.getExtras()
                .getString(CreateRoomActivity.EXTRA_ROOM_NAME);
            	
        		if(mRoomName.indexOf(DELIMITER) != -1){
        			mRoomName = mRoomName.replaceAll(DELIMITER, "!!");
        		}
        		
            	Toast.makeText(this, "Create a room : "+mRoomName, Toast.LENGTH_SHORT).show();
            	mTitle.setText(mRoomName);
            	
            } else {
                
                Toast.makeText(this, R.string.create_room_error, Toast.LENGTH_SHORT).show();
            } 
        	
        	break;
        
        case INTENT_FIND_ROOM:
        	if (resultCode == Activity.RESULT_OK ) {
	        	String mRoomToJoin = data.getExtras()
	            .getString(FindRoomActivity.EXTRA_JOIN_ROOM);
	        	
	        	if(mRoomToJoin != null && mRoomToJoin.length() > 0){
	        		
	        		if(mUserName != null)
	        			sendMessage(">>> "+mUserName +" leave !");
	        		
	        		mRoomName = mRoomToJoin;
	        		mTitle.setText(mRoomName);
	        		
	        		if(mUserName != null)
	        			sendMessage(">>> "+mUserName +" joined !");
	        	}
	        }
        	break;
        	**************************/
            
        }// end switch
    }

    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        
        inflater.inflate(R.menu.groupchat_menu, menu);
        
        return true;
    }


    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	
        switch (item.getItemId()) {
        
        case R.id.occupants:
        	
        	// Start a private chat with another participant
            //Chat chat = muc2.createPrivateChat("stylefish@conference.push.appaas.com/nevertry");
            //chat.sendMessage("Hello there");
        	
        	String occupants = "";
        	Iterator<String> itr = mMuc.getOccupants();
            
            while(itr.hasNext()) {
            	String occupant = itr.next();
            	
            	String fromResource = StringUtils.parseResource(occupant);
        		String fromName = StringUtils.parseBareAddress(fromResource);
        		if (fromName.equals(mNickname)) {
        			occupants = occupants + "  " + fromName + " " + getResources().getString(R.string.occupants_me) + "\n\n";
        		} else {
        			occupants = occupants + "  " + fromName + "\n\n";
        		}
            }
        	
        	
        	// custom dialog
			final Dialog dlg = new Dialog(activity);
			dlg.setContentView(R.layout.popup2);
			String title = getResources().getString(R.string.occupants);
			dlg.setTitle(title);
 
			// set the custom dialog components - text, image and button
			TextView text = (TextView) dlg.findViewById(R.id.text);
			text.setText(occupants);
			ImageView image = (ImageView) dlg.findViewById(R.id.image);
			image.setImageResource(R.drawable.ic_launcher);
 
			Button dialogButton = (Button) dlg.findViewById(R.id.dialogButtonOK);
			// if button is clicked, close the custom dialog
			dialogButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dlg.dismiss();
				}
			});
 
			dlg.show();
        	
        	return true;
        
        /*	
        case R.id.reg_image:
        	

        	if (imageChooser == null) {
        		imageChooser = new AlertDialogImageChooser(this, CHOOSER_IMAGE_REQUEST_CODE);
        	}
        	
        	// Optional
        	imageChooser.saveImageTo(StorageOption.SD_CARD_APP_ROOT, "myDirectory", "myFabulousImage");
        	
        	imageChooser.show();
        	
        	
        	
        	
        	return true;
        */	
        	
        case R.id.username:
        	/*
            // Launch the UserNameActivity to see devices and do scan
            Intent userNameIntent = new Intent(this, UserNameActivity.class);
            startActivityForResult(userNameIntent, INTENT_GET_USERNAME); 
            */
        	
        	/*
        	Intent takePic = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(takePic, LOAD_IMAGE_GALLERY);
            */
        	
        	

        	String picturePath = "/mnt/sdcard/DCIM/1km/2605567_111265912.jpg";

            
            //FileTransferManager manager = new FileTransferManager(connection);
        	
        	ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
            if (sdm == null)
            	sdm = new ServiceDiscoveryManager(connection);
            sdm.addFeature("http://jabber.org/protocol/disco#info");
            sdm.addFeature("jabber:iq:privacy");

            FileTransferNegotiator.setServiceEnabled(connection, true);
            
            
            // Create the file transfer manager
            FileTransferManager manager = new FileTransferManager(connection);

            
            OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer("nevertry@push.appaas.com");
            File file = new File(picturePath);
            try {
               transfer.sendFile(file, "test_file");
            } catch (XMPPException e) {
               e.printStackTrace();
            }
            
           
            
            while (!transfer.isDone()) {
               if(transfer.getStatus().equals(FileTransfer.Status.error)) {
                  //System.out.println("ERROR!!! " + transfer.getError());
                  if(D) Log.d(TAG, "ERROR!!! " + transfer.getError());
               } else if (transfer.getStatus().equals(FileTransfer.Status.cancelled)
                                || transfer.getStatus().equals(FileTransfer.Status.refused)) {
                  //System.out.println("Cancelled!!! " + transfer.getError());
            	   if(D) Log.d(TAG, "Cancelled!!! " + transfer.getError()); 
               }
               try {
                  Thread.sleep(1000L);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }
            if (transfer.getStatus().equals(FileTransfer.Status.refused) || transfer.getStatus().equals(FileTransfer.Status.error)
             || transfer.getStatus().equals(FileTransfer.Status.cancelled)){
               //System.out.println("refused cancelled error " + transfer.getError());
            	if(D) Log.d(TAG, "refused cancelled error " + transfer.getError());
            } else {
               //System.out.println("Success");
               if(D) Log.d(TAG, "Success");
            }
            
            
            return true;
            
        case R.id.createroom:
        	/*
        	// Launch the CreateRoomActivity to see devices and do scan
            Intent createRoomIntent = new Intent(this, CreateRoomActivity.class);
            startActivityForResult(createRoomIntent, INTENT_CREATE_ROOM);
            */
        	return true;
        	
        case R.id.findroom:
        	
        	/*
        	// Launch the CreateRoomActivity to see devices and do scan
        	
        	findRoom();
        	*/
        	return true;
        }

        
        return false;
    }
    
    
    
    
    /*
    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
        	
        	if(D) Log.d(TAG, "[handleMessage !!!!!!!!!!!! ]");
        	
            switch (msg.what) {
            
	            case MESSAGE_WRITE:
	          
					try {
						byte[] writeBuf = (byte[]) msg.obj;
		                // construct a string from the buffer
		                String writeMessage = new String(writeBuf);
		                ChatMessageChecker mc = new ChatMessageChecker (writeMessage);
		                
		                if(mc.getCmd().equals( CMD_MESSAGE ))
		                	mConversationArrayAdapter.add(mc.getMessageBody());
		                
					} catch (Exception e1) {
						e1.printStackTrace();
					} 
	                break;
	            case MESSAGE_READ:
	                String readBuf = (String) msg.obj;
	                
					try {
						
						ChatMessageChecker mc = new ChatMessageChecker(readBuf);
						
						if(mc.getCmd().equals(CMD_FIND_ROOM)){
							
						
							///////sendRoomNameAck();
							
							
						}else if(mc.getCmd().equals(CMD_ROOM_NAME_ACK)){
							
							if(existingRoomList != null){
								if(!existingRoomList.contains(mc.getRoomName()))
									existingRoomList.add(mc.getRoomName());
							}
							
						}else if(mc.getCmd().equals(CMD_MESSAGE)){
							if(mRoomName != null &&  mRoomName.equals(mc.getRoomName())){
								mConversationArrayAdapter.add(mc.getMessageBody());
							}else{
								if(D)Log.d(TAG,"Message from other room : "+mc.getRoomName()+"/"+mc.getMessageBody());
							}
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
					
	                break;               
	            case MESSAGE_TOAST:
	                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
	                               Toast.LENGTH_SHORT).show();
	                break;
            }
        }
    };    
    */
    


    class ChatMessageChecker{
    	String cmd 	= null;
    	String room = null;
    	String body = null;
    	
    	public ChatMessageChecker(String message) throws Exception{
    		
    		StringTokenizer st 	= new StringTokenizer(message,DELIMITER);
    		while(st.hasMoreElements()){
    			String token =  st.nextToken();
    			if(token.startsWith(CMD)){
    				cmd = token.substring(token.indexOf(CMD)+CMD.length());
    				continue;
    			}
    			
    			if(token.startsWith(ROOM)){
    				room = token.substring(token.indexOf(ROOM)+ROOM.length());
    				continue;
    			}
    			if(token.startsWith(BODY)){
    				body = message.substring(message.indexOf(BODY)+BODY.length());
    				continue;
    			}
    		}
    	}
    	
	    private String getRoomName(){
	    	return room;
	    } 
    
	    private String getCmd(){
	    	return cmd;
	    } 
    
	    private String getMessageBody(){
	    	return body;
	    }
    }
    
    
    class ChatMessageBuilder{
    	String message 	= null;
    	
    	public ChatMessageBuilder(String cmd) throws Exception{
    		this(cmd,null,null);
    	}
    	
    	public ChatMessageBuilder(String cmd, String roomName) throws Exception{
    		this(cmd,roomName,null);
    	}
    	
    	public ChatMessageBuilder(String cmd, String room, String body) throws Exception{    
    		if(cmd != null && cmd.equals(CMD_FIND_ROOM)){
    			message = 	CMD + CMD_FIND_ROOM;	
    		}else if (cmd != null && cmd.equals(CMD_ROOM_NAME_ACK) && room !=null){
    			message = 	CMD + CMD_ROOM_NAME_ACK + DELIMITER + ROOM + room;
    		}else if(cmd != null && room != null && body != null){
    			message = CMD + CMD_MESSAGE + DELIMITER + ROOM + room + DELIMITER + BODY +  body;
    		}
    	}
    	
	    private String getMessage(){
	    	return message;
	    }    
    }
    

    
    private void setListAdapter() {
        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item, messages);

        
    	
    	DiscussArrayAdapter adapter = new DiscussArrayAdapter(this, R.layout.listitem_discuss, messages);
        
        mConversationView.setAdapter(adapter);
        
        mConversationView.setSelection(adapter.getCount() -1);
        
        
    }
    
    
    
    private class SendMessage extends AsyncTask<Void, String, String>
	{
		@Override
		protected String doInBackground(Void... params) {
			
			
			return "";
		}
		@Override
		public void onProgressUpdate(String... v) {
			
			mAdapter.notifyDataSetChanged();
    		mConversationView.setSelection(messages.size()-1);
		}
		@Override
		protected void onPostExecute(String text) {

			
		}
		

	}
    
    
    /*
    public Handler mHandler = new Handler(){ 
	    public void handleMessage(android.os.Message msg){
	    	
	        switch(msg.what){ 
	            case 1:
	                set_timer(); 
	                break;
	            case 2:  
	                break;
	            case 3:
	                break;
	        }
	        
	        
	    	mAdapter.notifyDataSetChanged();
    		mConversationView.setSelection(messages.size()-1);
	    };
	};
	*/
    
    
    private final DefaultParticipantStatusListener participantStatusListener = new DefaultParticipantStatusListener() {
    
    	public void joined(String participant) {
            super.joined(participant);
            
            
            String msgText;
            String nickname = StringUtils.parseResource(participant);
    		
    		msgText = nickname + getResources().getString(R.string.room_joined);

    		messages.add(new OneComment(true, "", msgText));
    		if (messages.size() > 100) { messages.remove(0); }
    	
    		// Add the incoming message to the list view
    		mHandler.post(new Runnable() {
    			public void run() {
    				//setListAdapter();
    				mAdapter.notifyDataSetChanged();
            		mConversationView.setSelection(messages.size()-1);
    			}
    		});
            
        }
        public void left(String participant) {
            super.left(participant);
            
            
            String msgText;

            String nickname = StringUtils.parseResource(participant);
    		
    		msgText = nickname + getResources().getString(R.string.room_left);

    		messages.add(new OneComment(true, "", msgText));
    		if (messages.size() > 100) { messages.remove(0); }
    		
    		// Add the incoming message to the list view
    		mHandler.post(new Runnable() {
    			public void run() {
    				//setListAdapter();
    				mAdapter.notifyDataSetChanged();
            		mConversationView.setSelection(messages.size()-1);
    			}
    		});
            
        }
    };
    
     private final PacketListener packetListener = new PacketListener() {
    	
        public void processPacket(Packet packet) {
        	
        	if (packet instanceof Message) {
                // do something
        		Message message = (Message) packet;
        		
        		
        		//if(D) Log.e(TAG, message.getFrom() );
        		
        		
        		if (message.getBody() != null) {
                	
                	if (message.getType() == Message.Type.groupchat) {

                		String fromResource = StringUtils.parseResource(message.getFrom());
                		String fromName = StringUtils.parseBareAddress(fromResource);

                
                		//String tt = "CHAT", "Got text [" + message.getBody() + "] from [" + fromName + "]";
                		//if(D) Log.e(TAG, message.getFrom() );
                    

                    	////////if (fromName.equals(mNickName)) {
                    		/*
                    		String msgText;
                    		msgText = message.getBody();
               
                    		messages.add(new OneComment(false, msgText));
                    		if (messages.size() > 100) { messages.remove(0); }
                    		// Add the incoming message to the list view
                    		mHandler.post(new Runnable() {
                    			public void run() {
                    				setListAdapter();
                    			}
                    		});
                    		 */
                    	////////} else {
                    		
                    		String msgText;
                    		msgText = message.getBody();
             
                    		
                    		messages.add(new OneComment(true, fromName, msgText));
                    		if (messages.size() > 100) { messages.remove(0); }
                    		
                    		 //android.os.Message m = new android.os.Message();

                             //mHandler.sendMessage(m);
                    		
                    		
                    		//if (messages.size() > 25) {
                    		if (dialog == null) {	
                    			if(D) Log.e(TAG, "notifyDataSetChanged" );
                    			
                    			// Add the incoming message to the list view
                    			mHandler.post(new Runnable() {
                    				public void run() {
                    					//setListAdapter();
                    					mAdapter.notifyDataSetChanged();
                    					mConversationView.setSelection(messages.size()-1);
                    				}
                    			});
                    		//////////}
                    		
                    		//SendMessage sendMsg = new SendMessage();
                    		//sendMsg.execute();
                    		
                    		
                    		
                    		
                    		/*
                    		mConversationView.post(new Runnable() {
                    	        public void run() {
                    	            // the desired UI update 
                    	        	mAdapter.notifyDataSetChanged();
                            		mConversationView.setSelection(messages.size()-1);
                    	        }
                    	    });
                    		*/
                    		
                    		/*
                    		messages.add(new OneComment(true, msgText));
                    		if (messages.size() > 100) { messages.remove(0); }
                    		//new SendMessage().execute();
                    		
                    		Thread t = new Thread(new Runnable(){
                            	@Override
                            	public void run() {
                            		
                            		// no UI
                            		mHandler.post(new Runnable(){
                            			@Override
                            			public void run() {
                            				// UI OK
                            				
                                    		mAdapter.notifyDataSetChanged();
                                    		mConversationView.setSelection(messages.size()-1);
                            			}
                            		});
                            	}
                            	
                            });
                            
                            t.start();
                    		*/
                    		
                    
                    	}
                    
                	} else {
                		
                		String fromResource = StringUtils.parseResource(message.getFrom());
                    	
                    	
                		String fromName = StringUtils.parseBareAddress(fromResource);
                		
                		
                		String msgText;
                		msgText = "(" + getResources().getString(R.string.whisper) + ")" + message.getBody();
           
                		messages.add(new OneComment(true, fromName, msgText));
                		if (messages.size() > 100) { messages.remove(0); }
                		
                		// Add the incoming message to the list view
                		mHandler.post(new Runnable() {
                			public void run() {
                				setListAdapter();
                			}
                		});
                	}
        		
        		}
        		
        		
        		
            } else if (packet instanceof Presence) {
              // do something else
            	
            	Presence presence = (Presence) packet;
                
                
                	
                    		String msgText;
                    		msgText = presence.getMode().toString();
               
                    		messages.add(new OneComment(true, presence.getFrom(), msgText));
                    		if (messages.size() > 100) { messages.remove(0); }
                    		
                    		
                    		// Add the incoming message to the list view
                    		mHandler.post(new Runnable() {
                    			public void run() {
                    				setListAdapter();
                    			}
                    		});
                
                
                
                
            }

        	
        	
            
        }
    };
    
    
    /**
     * Called by Settings dialog when a connection is establised with the XMPP server
     *
     * @param connection
     */
    public void setConnection(XMPPConnection connection) {
        
    	this.connection = connection;
    
      	// Add a packet listener to get messages sent to us
        PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
    	
        //PacketFilter filter = new OrFilter(new MessageTypeFilter(Message.Type.groupchat), 
        	//	new MessageTypeFilter(Message.Type.chat));
    	
        //new OrFilter(new PacketTypeFilter(Message.class), new PacketTypeFilter(Presence.class ))
        
   
        
        connection.addPacketListener(new PacketListener() {
        	
            public void processPacket(Packet packet) {
            	
                Message message = (Message) packet;
                
                if (message.getBody() != null) {
                    
                	
                	if(D) Log.e(TAG, "private chat from " + message.getFrom());
                	
                	
                	String fromResource = StringUtils.parseResource(message.getFrom());
                	
            		String fromName = StringUtils.parseBareAddress(fromResource);
                	
                	//String tt = "CHAT", "Got text [" + message.getBody() + "] from [" + fromName + "]";
                    if(D) Log.e(TAG, "private chat from " + fromName);
                    
 
 

 
                
                    
                    if (mDashDialog.isShowing() == false) {
                    	mDashDialog.setContentView(R.layout.popup2);
                    	
                    	String title = fromName + getResources().getString(R.string.whisper);
                    	mDashDialog.setTitle(title);
    	 
                    	// set the custom dialog components - text, image and button
                    	TextView text = (TextView) mDashDialog.findViewById(R.id.text);
                    	text.setText(message.getBody());
                    	ImageView image = (ImageView) mDashDialog.findViewById(R.id.image);
                    	image.setImageResource(R.drawable.ic_launcher);
    	 
                    	Button dialogButton = (Button) mDashDialog.findViewById(R.id.dialogButtonOK);
                    	// if button is clicked, close the custom dialog
                    	dialogButton.setOnClickListener(new OnClickListener() {
                    		@Override
                    		public void onClick(View v) {
                    			mDashDialog.dismiss();
                    		}
                    	});
    	 
                    	//dlg.show();
                    	mHandler.post(new Runnable() {
                    		public void run() {
                    			mDashDialog.show();
                    		}
                    	});
                    
                    }
                    
                   
                    
                    /*
                    messages.add(new OneComment(true, fromName));
                    if (messages.size() > 100) { messages.remove(0); }
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                		}
                	});
                	*/

                }
                
                
            }
        }, filter);
    
    
    }
    
    
    
    
    
    //private void configure(ProviderManager pm) {
    private void configure() {
		 
    	ProviderManager pm = ProviderManager.getInstance();
    	
        //  Private Data Storage
        pm.addIQProvider("query","jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());
 
        //  Time
        try {
            pm.addIQProvider("query","jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
        } catch (ClassNotFoundException e) {
            Log.w("TestClient", "Can't load class for org.jivesoftware.smackx.packet.Time");
        }
 
        
        //  Roster Exchange
        pm.addExtensionProvider("x","jabber:x:roster", new RosterExchangeProvider());
 
        //  Message Events
        pm.addExtensionProvider("x","jabber:x:event", new MessageEventProvider());
 
        //  Chat State
        pm.addExtensionProvider("active","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("composing","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("paused","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("inactive","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("gone","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        //  XHTML
        //////////pm.addExtensionProvider("html","http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());
 
        //  Group Chat Invitations
        pm.addExtensionProvider("x","jabber:x:conference", new GroupChatInvitation.Provider());
 
        //  Service Discovery # Items    
        pm.addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
 
        //  Service Discovery # Info
        pm.addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
 
        //  Data Forms
        pm.addExtensionProvider("x","jabber:x:data", new DataFormProvider());
 
        //  MUC User
        pm.addExtensionProvider("x","http://jabber.org/protocol/muc#user", new MUCUserProvider());
 
        //  MUC Admin    
        pm.addIQProvider("query","http://jabber.org/protocol/muc#admin", new MUCAdminProvider());
 
 
        //  MUC Owner    
        pm.addIQProvider("query","http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());
 
        //  Delayed Delivery
        pm.addExtensionProvider("x","jabber:x:delay", new DelayInformationProvider());
 
        //  Version
        try {
            pm.addIQProvider("query","jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
        } catch (ClassNotFoundException e) {
            //  Not sure what's happening here.
        }
 
        //  VCard
        pm.addIQProvider("vCard","vcard-temp", new VCardProvider());
 
        //  Offline Message Requests
        pm.addIQProvider("offline","http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
 
        //  Offline Message Indicator
        pm.addExtensionProvider("offline","http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
 
        //  Last Activity
        pm.addIQProvider("query","jabber:iq:last", new LastActivity.Provider());
 
        //  User Search
        pm.addIQProvider("query","jabber:iq:search", new UserSearch.Provider());
 
        //  SharedGroupsInfo
        pm.addIQProvider("sharedgroup","http://www.jivesoftware.org/protocol/sharedgroup", new SharedGroupsInfo.Provider());
 
        //  JEP-33: Extended Stanza Addressing
        pm.addExtensionProvider("addresses","http://jabber.org/protocol/address", new MultipleAddressesProvider());
 		
 
       
        //   FileTransfer
        
        pm.addIQProvider("si","http://jabber.org/protocol/si", new StreamInitiationProvider());
 
        
        pm.addIQProvider("query","http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
 
        //pm.addIQProvider("open","http://jabber.org/protocol/ibb", new IBBProviders.Open());
        //pm.addIQProvider("close","http://jabber.org/protocol/ibb", new IBBProviders.Close());
        //pm.addExtensionProvider("data","http://jabber.org/protocol/ibb", new IBBProviders.Data());
 		
        
        pm.addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
        pm.addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());

    
        
        
        //  Privacy
        pm.addIQProvider("query","jabber:iq:privacy", new PrivacyProvider());
 
        pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
        pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.MalformedActionError());
        pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadLocaleError());
        pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadPayloadError());
        pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadSessionIDError());
        pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.SessionExpiredError());
    
        /*
        // PubSub
        pm.addIQProvider(
                "query", "http://jabber.org/protocol/disco#items",
                 new org.jivesoftware.smackx.provider.DiscoverItemsProvider()
            );
            
            pm.addIQProvider("query",
                    "http://jabber.org/protocol/disco#info",
                    new org.jivesoftware.smackx.provider.DiscoverInfoProvider());
            
            pm.addIQProvider("pubsub",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.PubSubProvider());

            pm.addExtensionProvider("subscription", PubSubNamespace.BASIC.getXmlns() , new SubscriptionProvider());
            
            pm.addExtensionProvider(
                    "create",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            
            pm.addExtensionProvider("items",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.ItemsProvider());
            
            pm.addExtensionProvider("item",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());
            
            pm.addExtensionProvider("item", "",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());
            
            pm.addExtensionProvider(
                            "subscriptions",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.SubscriptionsProvider());

            pm.addExtensionProvider(
                            "subscriptions",
                            "http://jabber.org/protocol/pubsub#owner",
                            new org.jivesoftware.smackx.pubsub.provider.SubscriptionsProvider());

            pm.addExtensionProvider(
                            "affiliations",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.AffiliationsProvider());
            
            pm.addExtensionProvider(
                            "affiliation",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.AffiliationProvider());
            
            pm.addExtensionProvider("options",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addIQProvider("pubsub",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.PubSubProvider());
            
            pm.addExtensionProvider("configure",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addExtensionProvider("default",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());


            pm.addExtensionProvider("event",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.EventProvider());
            
            pm.addExtensionProvider(
                            "configuration",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.ConfigEventProvider());
            
            pm.addExtensionProvider(
                            "delete",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            
            pm.addExtensionProvider("options",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addExtensionProvider("items",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.ItemsProvider());
            
            pm.addExtensionProvider("item",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());

            pm.addExtensionProvider("headers",
                    "http://jabber.org/protocol/shim",
                    new org.jivesoftware.smackx.provider.HeaderProvider());

            pm.addExtensionProvider("header",
                    "http://jabber.org/protocol/shim",
                    new org.jivesoftware.smackx.provider.HeadersProvider());
            
            
            pm.addExtensionProvider(
                            "retract",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.RetractEventProvider());
            
            pm.addExtensionProvider(
                            "purge",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            

         */


            SmackConfiguration.setKeepAliveInterval(-1);
     
		
	}
 
    
    
    /** A method to download xml data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
                URL url = new URL(strUrl);
                
                // Creating an http connection to communicate with url 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();
                
                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                
                StringBuffer sb  = new StringBuffer();
                
                String line = "";
                while( ( line = br.readLine())  != null){
                	sb.append(line);
                }
                
                
                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
                if(D) Log.e(TAG, e.toString());
        }finally{
                iStream.close();
        }

        return data;
    }
    
 
}




